package me.shibor.study.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 获取初始化参数;
 * 3种请求重定向;
 * 
 * @author shibor
 *
 */
public class HttpServletDemo extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {

		System.out.println("HttpServletDemo init()");
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {

		Enumeration<String> initParameterNames = config.getInitParameterNames();
		
		while(initParameterNames.hasMoreElements()) {
			String nextElement = initParameterNames.nextElement();
			String initParameter = config.getInitParameter(nextElement);
			System.out.println(nextElement + ": " + initParameter);
		}
	}	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//resp.getOutputStream().write("doGet方法调用".getBytes());
		PrintWriter out = resp.getWriter();
		out.print("<h2>myServlet include</h2>");
		//1.sendRedirect请求重定向
		//resp.sendRedirect("http://www.baidu.com");
		
		//2、forward 请求转发，不包含当前
		//req.getRequestDispatcher("hello").forward(req, resp);
		
		//3、include 请求转发，包含当前
		req.getRequestDispatcher("hello").include(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		resp.getOutputStream().write("doPut方法调用".getBytes());
		
	}
	
	

}
